package org.sczfdf;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.thread.ThreadUtil;
import org.sczfdf.conf.GitConf;
import org.sczfdf.conf.GlobalConf;
import org.sczfdf.conf.LogConf;
import org.sczfdf.conf.MailConf;
import org.sczfdf.conf.WatchConf;
import org.sczfdf.utils.GitUtil;
import org.sczfdf.utils.LogUtil;
import org.sczfdf.utils.PropertiesUtil;
import org.sczfdf.utils.WatchUtil;

import java.util.ArrayList;
import java.util.List;

import static org.sczfdf.constants.Constant.WATCH_OTHER_CMD;

/**
 * @author Created by ${USER}
 * @date ${DATE}
 */
public class App {

    public static void main(String[] args) {
        init(args);

        // 文件改动时提交
        WatchUtil.watch();

        // 60分钟拉一次代码
        ThreadUtil.execute(() -> {
            Integer pullInterval = GitConf.get().getGitPullInterval();
            while (true) {
                GitUtil.pull();
                ThreadUtil.sleep(pullInterval * DateUnit.MINUTE.getMillis());
            }
        });

    }

    private static void init(String[] args) {
        List<String> watchOtherCmdList = new ArrayList<>();
        for (String arg : args) {
            if (!arg.startsWith("--S")) {
                continue;
            }

            String kv = arg.replace("--S", "");
            String[] split = kv.split("=");

            String key = split[0];
            String value = split[1];

            if (WATCH_OTHER_CMD.getKey().equals(key)) {
                watchOtherCmdList.add(value);

                String cmdJoin = String.join(",", watchOtherCmdList);
                value = "[" + cmdJoin + "]";
            }

            PropertiesUtil.setConf(key, value);
        }

        LogUtil.logInfo("config↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓");
        LogUtil.logInfo(BeanUtil.beanToMap(GlobalConf.get()));
        LogUtil.logInfo(BeanUtil.beanToMap(LogConf.get()));
        LogUtil.logInfo(BeanUtil.beanToMap(GitConf.get()));
        LogUtil.logInfo(BeanUtil.beanToMap(MailConf.get()));
        LogUtil.logInfo(BeanUtil.beanToMap(WatchConf.get()));
        LogUtil.logInfo("config↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑");

        WatchUtil.executeOtherCommand();
    }

}




